package com.tpe.model.cloud;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.ejb.AccessTimeout;
import javax.ejb.EJB;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;

import com.amazonaws.services.sqs.model.Message;
import com.tpe.model.entity.Usuario;
import com.tpe.model.enums.QueueEnum;
import com.tpe.model.service.UsuarioService;
import com.tpe.model.util.JsonUtil;

@Singleton
@Startup
public class VerifyUserQueue {

	private List<Message> messages = new ArrayList<Message>();

	@EJB private UsuarioService usuarioService;

	@Timeout
	@AccessTimeout(value = 3, unit = TimeUnit.MINUTES)
	@Schedule(second="*/30", minute="*", hour="*")
	public void queueChecksConfirmation() throws Exception {
		messages = QueueUtil.retrieveMessages(QueueEnum.QUEUE_RECEIVE_CONFIRMATION.getUrl());

		for(Message msg : messages){
			Usuario user = JsonUtil.usuarioToObj(msg.getBody());
			System.out.println(JsonUtil.usuarioToJson(user));

			user = usuarioService.obterPorEmail(user);
			user.setFlagConfirmado(true);
			usuarioService.atualizar(user);

			QueueUtil.deleteQueueItem(msg, QueueEnum.QUEUE_RECEIVE_CONFIRMATION.getUrl());
		}
	}
}